
--lunomobs = {}
lunomobs.trader1 = {}
lunomobs.trader1.local_da_loja = {}
lunomobs.trader1.formspec = {
	customer = function(pos)
		--local list_name = "nodemeta:"..pos.x..','..pos.y..','..pos.z
		--local list_name = "detached:"..pos.x..','..pos.y..','..pos.z
		local list_name = "detached:modtrade1"
		--local list_name = "modtrade1"
		--local list_name = "modtrade1:"..pos.x..','..pos.y..','..pos.z
		local formspec = "size[8,9.5]"..
		"label[0,0; Você Oferece:]"..
		"list[current_player;customer_gives;0,0.5;3,2;]"..
		"label[0,2.5;Você Recebe:]"..
		"list[current_player;customer_gets;0,3;3,2;]"..
		"label[5,0;A Loja Precisa:]"..
		"list["..list_name..";owner_wants;5,0.5;3,2;]"..
		"label[5,2.5;A Loja Oferece:]"..
		"list["..list_name..";owner_gives;5,3;3,2;]"..
		"label[0,5;Seu inventário atual:]"..
		"list[current_player;main;0,5.5;8,4;]"..
		"button[3,2;2,1;exchange;Aceitar]"
		return formspec
	end,
	owner = function(pos)
		--local list_name = "nodemeta:"..pos.x..','..pos.y..','..pos.z
		--local list_name = "detached:"..pos.x..','..pos.y..','..pos.z
		local list_name = "detached:modtrade1"
		--local list_name = "modtrade1"
		--local list_name = "modtrade1:"..pos.x..','..pos.y..','..pos.z
		local formspec = "size[8,9.5]"..
		"label[0,0;Itens Recebido (Seu Lucro):]"..
		"list["..list_name..";customers_gave;0,0.5;3,2;]"..
		"label[0,2.5;Estoque à Oferetar:]"..
		"list["..list_name..";stock;0,3;3,2;]"..
		"label[5,0;Você Precisa:]"..
		"list["..list_name..";owner_wants;5,0.5;3,2;]"..
		"label[5,2.5;Você Oferece:]"..
		"list["..list_name..";owner_gives;5,3;3,2;]"..
		--"label[0,5;Proprietário: Pressione (E) + Botão(RMB) no Mouse para a interface com o cliente]"..
		--"label[0,5;Vendedor: Evite o estoque baixo e guardar lucros no balcão.]"..
		"label[0,5;Seu inventário atual:]"..
		"list[current_player;main;0,5.5;8,4;]"
		return formspec
	end,
}


lunomobs:register_mob("lunomobs:trader1", {
	type = "npc",
	--random_names = { "Greenstone","Rhanatar","Bhramir","Sendhor","Calamir"},
	random_names = { "Selena","Selina","Selia","Sena","Shanna"},
	hp_max = 6, --Padrão = 4
	visual = "mesh",
	mesh="mobs_humanoid.b3d",
	--textures = {"mobs_humanoid_trader.png"},
	textures = {"mobs_humanoid_girl_pink.png"},
	--textures = {"mobs_humanoid_lupin_of_harry_potter.png"},
	--visual_size = {x=8,z=10},
	collisionbox = {-0.3,-1.0,-0.3, 0.3,0.8,0.3},
	visual_size= {x=1, y=1},
--	makes_footstep_sound = true,
	view_range = 10,
	walk_percent = 50,  --Probabilidade dele ficar andando. Varia de 0 ~ 100% do tempo
	walk_velocity = 1,
	--run_velocity = 1,
	--jump = false, --Comerciantes nao pulam!
	drops = { 
		--{name="lunomobs:coin", chance = 1, min=1, max=10,}, --Probabilidade é de 1:35 de cair entre 1 a 3 "minemoedas"
		{name="lunomobs:trader1", chance = 1, min=1, max=1 ,},	--Probabilidade é de 1:20 (5%) de cair entre 1 a 3 "punhados de ouro"
	},
	light_resistant = true,
	armor = 100,
	drawtype = "front", -- se o mesh fo idesenha do de lado(size) ou de frante
	water_damage = 1, --1=Morte lenta
	lava_damage = 10,
	light_damage = 0,
	--attack_type = "dogfight",
	animation = {
		speed_normal=15, 
		stand_start=0, stand_end=79,
		walk_start=168, walk_end=187,
--		punch_start=168, punch_end=187,
--		speed_run=15,
--		run_start=168, run_end=187,
	},
	--sounds={ random="mobs_hello",	},
--	follow = "lunomobs:coin",
	--FONTE: https://github.com/PilzAdam/mobs/wiki/API
--[[
	loja_atual = { },
	trader_inventory = {
		goods = {
			{ "default:furnace 1",		"default:cobble 3",	nil},
			{ "default:sword_steel 1", "default:cobble 4",	"default:stone 20"},
			{ "bucket:bucket_empty 1", "default:cobble 10",	"default:stone 2"},
			{ "default:chest 1", 		"default:cobble 2",	"default:stone 10"},
		},
		random_names = { "Lunovox","Stately",},
	},
--]]
--[[
	on_activate = function(self, staticdata, dtime_s)
		if staticdata then
			local tmp = minetest.deserialize(staticdata)
			if tmp and tmp.owner then
				self.owner = tmp.owner
			end
		end
	end,
--]]
	on_rightclick = function(self, user)
		if self.selected_name == nil or self.selected_name == "" then
			self.selected_name = self.random_names[math.random(1, #self.random_names)]
		end
		
		
		
		if self.owner == nil or self.owner == "" then
			self.owner = user:get_player_name()
		end

--[[
		--function(pos, node, clicker, itemstack)
		user:get_inventory():set_size("customer_gives", 3*2)
		user:get_inventory():set_size("customer_gets", 3*2)
		--lunotrades.balcaodeloja.loja_atual = {}
		--self.loja_atual[user:get_player_name()] = self.pos
		
		--local meta = minetest.env:get_meta(pos)
		if user:get_player_name() == self.owner and not user:get_player_control().aux1 then
			minetest.show_formspec(user:get_player_name(),"lunomobs.trader1_formspec",lunomobs.trader1.formspec.owner(pos))
		else
			minetest.show_formspec(user:get_player_name(),"lunomobs.trader1_formspec",lunomobs.trader1.formspec.customer(pos))
		end
--]]


--[[
		formspec = "size[8,9]"..
			"list[trader1;main;0,0;8,4;]"..
			"list[current_player;main;0,5;8,4;]"
		minetest.show_formspec(user:get_player_name(),"trader1:mainform",formspec)
		minetest.register_on_player_receive_fields(function(player, formname, fields)
			fields["trader1"]
		
		end)
]]		
		--on_receive_fields = def.on_receive_fields,

		local falas = { }
		falas[#falas+1] = "Olá "..user:get_player_name().."!"
		falas[#falas+1] = "Você precisa compra algo?"
		falas[#falas+1] = "Você pode comprar clicando como o segundo botão do \nmouse sobre o 'Balcao da Loja de "..self.owner.."'."


		local fala_atual = 1
		self.fixed_y = true
		self.walk_velocity = 0
		self.set_velocity(self, 0)
		self.jump = false
		self.state = "stand"
		self:set_animation("stand")
		self.object:setyaw(user:get_look_yaw() + (math.pi /2))
		minetest.sound_play("mobs_hello_female", {pos=user.pos, max_hear_distance = 5}) --toca som "mobs_sheep".ogg a distancia de 5 blocos do usuário.

		minetest.show_formspec(user:get_player_name(),"lunomobs.trader1_formspec",
			"size[8,3]"..
			--"label[0.5,0;"..self.trader_inventory.random_names[1]..":]"..
			"textarea[0.25,0.25;8,3;txtArea;"..self.selected_name.." diz:;"..falas[fala_atual].."]"..
			"button[3,2.5;2,1;next;Avançar]"
		)
		
		minetest.register_on_player_receive_fields(function(sender, formname, fields)
			--[[
			minetest.chat_send_player(sender:get_player_name(), 
				"sender:get_player_name()='"..sender:get_player_name() .."' "..
				"formname='"..formname .."' "..
				"fields='"..dump(fields).."' "
			,false)
			--]]
			if formname == "lunomobs.trader1_formspec" and fields.closer == nil then
				fala_atual = fala_atual + 1
				self.doCallMob(self, sender, true)
				if fala_atual < #falas then
					minetest.show_formspec(sender:get_player_name(),"lunomobs.trader1_formspec",
						"size[8,3]"..
						--"label[0.5,0;"..self.trader_inventory.random_names[1]..":]"..
						"textarea[0.25,0.25;8,3;txtArea;"..self.selected_name.." diz:;"..falas[fala_atual].."]"..
						"button[3,2.5;2,1;next;Avançar]"
					)
				elseif fala_atual == #falas then
					minetest.show_formspec(sender:get_player_name(),"lunomobs.trader1_formspec",
						"size[8,3]"..
						--"label[0.5,0;"..self.trader_inventory.random_names[1]..":]"..
						"textarea[0.25,0.25;8,3;txtArea;"..self.selected_name.." diz:;"..falas[fala_atual].."]"..
						"button_exit[3,2.5;2,1;closer;Fechar]"
					)
					--fala_atual = 0
				end
			else
				self.doCallMob(self, user, false)
			end
			return true --Se a função volta true ele não será chamada até ser reinstanciada.
		end)

--[[
		local falas = { }
		falas[#falas+1] = "Olá "..user:get_player_name().."!"
		falas[#falas+1] = "Esta cidade é muito segura."
		falas[#falas+1] = "Mais tarde irei passar na loja para comprar suprimentos."
		falas[#falas+1] = "Um dia esta mulher se apaixonará por mim. (^.^)"
		falas[#falas+1] = "Você tem relógio "..user:get_player_name().."?"
		minetest.chat_send_player(user:get_player_name(), "<"..self.trader_inventory.random_names[1] .."> "..tostring(falas[math.random(1, #falas)]),false)
--]]
	end,
})


function lunomobs:get_nome(entity)
	--return entity.data.trader_inventory.random_names[#entity.data.trader_inventory.random_names]
	return entity.trader_inventory.random_names[#entity.trader_inventory.random_names]
	
	--entity.object:get_properties("trader_inventory")

end

--lunomobs:register_spawn("lunomobs:trader1", {"default:dirt_with_grass", "default:grass_1", "default:grass_2", "default:grass_3", "default:grass_4", "default:grass_5"}, 20, -1, 7000, 3, 31000)





















	
function onInstaceTrade1(itemstack, placer, pointed_thing) --bugada
	if pointed_thing.above then
		local myInstance = minetest.env:add_entity(pointed_thing.above, "lunomobs:trader1")
		local myTrade1 = myInstance:get_luaentity()
		myTrade1.tamed = true
		myTrade1.selected_name = myTrade1.random_names[math.random(1, #myTrade1.random_names)]
		--myTrade1.textures = {"mobs_rat2.png"}
		myTrade1.owner = placer:get_player_name()
	
--[[
		local owner = placer:get_player_name()
		local meta = minetest.env:get_meta(pos)
		meta:set_string("infotext", "Loja de Escambo de '"..owner.."'")
		meta:set_string("owner",owner)
		--meta:set_string("pl1","") 
		--meta:set_string("pl2","")
		local inv = meta:get_inventory()
		inv:set_size("customers_gave", 3*2)
		inv:set_size("stock", 3*2)
		inv:set_size("owner_wants", 3*2)
		inv:set_size("owner_gives", 3*2)
--]]			

		--local list_name = "detached:"..pos.x..','..pos.y..','..pos.z
		--myTrade1.loja_atual = minetest.create_detached_inventory("test_inventory", {
			--"nodemeta:"..pointed_thing.above.x..','..pointed_thing.above.y..','..pointed_thing.above.z,
			--"detached:"..pointed_thing.above.x..','..pointed_thing.above.y..','..pointed_thing.above.z,  
		local nome_do_inventario = "modtrade1"
		--local nome_do_inventario = "detached:modtrade1"
		--local nome_do_inventario = "modtrade1:"..pointed_thing.above.x..','..pointed_thing.above.y..','..pointed_thing.above.z
		myTrade1.loja_atual = minetest.create_detached_inventory(nome_do_inventario,{
				allow_move = function(pos, from_list, from_index, to_list, to_index, count, player)
					--local meta = minetest.env:get_meta(pos)
					--if player:get_player_name() ~= meta:get_string("owner") then return 0 end
					if player:get_player_name() ~= myTrade1.owner then return 0 end
					return count
				end,
				allow_put = function(pos, listname, index, stack, player)
					--local meta = minetest.env:get_meta(pos)
					--if player:get_player_name() ~= meta:get_string("owner") then return 0 end
					if player:get_player_name() ~= myTrade1.owner then return 0 end
					return stack:get_count()
				end,
				allow_take = function(pos, listname, index, stack, player)
					--local meta = minetest.env:get_meta(pos)
					--if player:get_player_name() ~= meta:get_string("owner") then return 0 end
					if player:get_player_name() ~= myTrade1.owner then return 0 end
					return stack:get_count()
				end,
				on_move = function(inv, from_list, from_index, to_list, to_index, count, player)
					minetest.log(player:get_player_name().." moved items")
				end,
				on_put = function(inv, listname, index, stack, player)
					minetest.log(player:get_player_name().." put items")
				end,
				on_take = function(inv, listname, index, stack, player)
					minetest.log(player:get_player_name().." took items")
				end,
			}
		)
	
		myTrade1.loja_atual:set_size("customers_gave", 3*2)
		myTrade1.loja_atual:set_size("stock", 3*2)
		myTrade1.loja_atual:set_size("owner_wants", 3*2)
		myTrade1.loja_atual:set_size("owner_gives", 3*2)
		--self.loja_atual:set_size("main", 4*6)
		--self.loja_atual:add_item("main", "experimental:tester_tool_1")
		--self.loja_atual:add_item("main", "experimental:tnt 5")
	
--[[			]]
		placer:get_inventory():set_size("customer_gives", 3*2)
		placer:get_inventory():set_size("customer_gets", 3*2)
		lunomobs.trader1.local_da_loja[placer:get_player_name()] = myTrade1.object:getpos()
		--myTrade1.loja_atual[placer:get_player_name()] = myTrade1.object:getpos()
	
		--minetest.chat_send_all(myTrade1.name.."[".. myTrade1.object:getpos().x ..",".. myTrade1.object:getpos().y ..",".. myTrade1.object:getpos().z .."]")

		--minetest.log(placer:get_player_name().." aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

		if not placer:get_player_control().aux1 then
			minetest.show_formspec(placer:get_player_name(),"lunomobs.trader1_formspec",lunomobs.trader1.formspec.owner(myTrade1.object:getpos()))
		else
			minetest.show_formspec(placer:get_player_name(),"lunomobs.trader1_formspec",lunomobs.trader1.formspec.customer(myTrade1.object:getpos()))
		end
--]]
		if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end
	end
	return itemstack
end





function onInstaceTrade1b(itemstack, placer, pointed_thing)
	if pointed_thing.above then
		local myInstance = minetest.env:add_entity(pointed_thing.above, "lunomobs:trader1")
		local myTrade1 = myInstance:get_luaentity()
		myTrade1.tamed = true
		myTrade1.selected_name = myTrade1.random_names[math.random(1, #myTrade1.random_names)]
		--myTrade1.textures = {"mobs_rat2.png"}
		myTrade1.owner = placer:get_player_name()
		if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end
	end
	return itemstack
end












minetest.register_craftitem("lunomobs:trader1", {
	description = "Garota Balconista",
	groups = { mobs=1 },
	inventory_image = "mob_humanoid_girl_pink.png",
	on_place = onInstaceTrade1b,
})

minetest.register_alias("trader"				, "lunomobs:trader1")
minetest.register_alias("trader1"			, "lunomobs:trader1")
minetest.register_alias("balconista"		, "lunomobs:trader1")
minetest.register_alias("garotabalconista", "lunomobs:trader1")

--[[
minetest.register_on_player_receive_fields(function(sender, formname, fields)
	if formname == "lunotrades.balcaodeloja_formspec" then
		local name = sender:get_player_name()
		local pos = lunomobs.trader1.local_da_loja[name]
		
		
		
		
		
		
		
		minetest.chat_send_player(name,"Parada brusca para não bugar. Retirarei esta linha quando eu revisar as linhas abaixo.")
		return --Lunovox: Para não bugar. Retirarei esta linha quando eu revisar as linhas abaixo.
		
		
		
		
		
		
		
		
		
		local meta = minetest.env:get_meta(pos)
		if meta:get_string("owner") == name then
			minetest.chat_send_player(name,"Esta é a sua própria loja, você não pode trocar a si mesmo!")
		else
			local minv = meta:get_inventory()
			local pinv = sender:get_inventory()
			local invlist_tostring = function(invlist)
				local out = {}
				for i, item in pairs(invlist) do
					out[i] = item:to_string()
				end
				return out
			end
			local wants = minv:get_list("owner_wants")
			local gives = minv:get_list("owner_gives")
			if wants == nil or gives == nil then return end -- do not crash the server
			-- Check if we can exchange
			local can_exchange = true
			local owners_fault = false
			for i, item in pairs(wants) do
				if not pinv:contains_item("customer_gives",item) then
					can_exchange = false
				end
			end
			for i, item in pairs(gives) do
				if not minv:contains_item("stock",item) then
					can_exchange = false
					owners_fault = true
				end
			end
			if can_exchange then
				for i, item in pairs(wants) do
					pinv:remove_item("customer_gives",item)
					minv:add_item("customers_gave",item)
				end
				for i, item in pairs(gives) do
					minv:remove_item("stock",item)
					pinv:add_item("customer_gets",item)
				end
				minetest.chat_send_player(name,"Escambo feito!")
			else
				if owners_fault then
					minetest.chat_send_player(name,"O estoque de '"..meta:get_string("owner").."' acabou. Contacte-o!")
				else
					minetest.chat_send_player(name,"O escambo não pode ser feito. Verifique se você ofereceu o que a loja pede!")
				end
			end
		end

	end
end)

]]
